<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/5/22 0022
 * Describe: 订单管理类.
 */

namespace app\common\model;
use think\Db;
use think\Model;
use app\common\controller\order\Orderget;

class Order extends Model
{
    /**
     * 根据借款金额获取借款产品信息.
     *
     * @param string $postData
     *
     * @return array
     */
    public function getMoneyOrderInfo($loanMoeny)
    {
        return db('goods')->where(['IsShelves' => 1, 'SalePrice' => $loanMoeny])->find();
    }

    /**
     * 获取最大额度产品
     */
    public function getMaxGoods()
    {
        return db('goods')->where(['IsShelves' => 1])->max('SalePrice');
    }

    public function getMinGoods()
    {
        return db('goods')->where(['IsShelves' => 1])->min('SalePrice');
    }

    /**
     * 根据订单ID获取订单信息.
     *
     * @param int $orderId 订单ID
     *
     * @return array
     */
    public function getIdOrderInfo($orderId)
    {
        return db('loans_applylist')->where(['ID|OrderSn' => $orderId])->find();
    }

    /**
     * 获取订单应还款金额.
     *
     * @param int $orderInfo 订单信息
     */
    public function getOrderShould($orderInfo)
    {
        //检测订单是否逾期并获取逾期天数
        $isOrderOverdue = $this->isOrderOverdue($orderInfo);
        if ($isOrderOverdue) {
            //最终还款金额 = 到期应还金额 + 逾期金额
            $orderInfo['daoqiMoney'] = $orderInfo['daoqiMoney'] + $this->getOrderPenalty($orderInfo);
        }

        //获取用户部分还款金额
        $partMoney = $this->getOrderPartMoney($orderInfo);

        //获取用户豁免金额
        $reductionMoney = $this->getOrderReductionMoney($orderInfo);

        //最终还款金额
        return (int) $orderInfo['daoqiMoney'] - ($partMoney + $reductionMoney);
    }

    /**
     * 检测订单是否逾期
     *
     * @param array $orderInfo 订单信息
     * @param bool  $isLimit   是否加入系统最大可逾期天数判断
     *
     * @return int 逾期天数
     */
    public function isOrderOverdue($orderInfo, $isLimit = true)
    {
        $overtimes = date('Y-m-d', strtotime($orderInfo['YyFkTime'])).' 23:59:59';

        //检测是否逾期并返回逾期天数
        if (strtotime($overtimes) < strtotime(date('Y-m-d'))) {
            //获取逾期天数并根据是否根据系统最大可逾期天数 获取订单实际逾期天数
            $days = diffBetweenTwoDays($overtimes, date('Y-m-d'));
            if ($isLimit) {
                $systemDays = (new System())->getSystemInfo();

                return ($days > $systemDays['yuqijifeidays']) ? $systemDays['yuqijifeidays'] : $days;
            } else {
                return $days;
            }
        }

        return 0;
    }

    /**
     * 计算逾期订单逾期罚息.
     *
     * @param araay $orderInfo
     *
     * @return int 订单逾期罚息
     */
    public function getOrderPenalty($orderInfo)
    {
        //检测订单是否逾期并获取逾期天数
        $isOrderOverdue = $this->isOrderOverdue($orderInfo);
        if ($isOrderOverdue) {
            //订单逾期 返回逾期金额 订单申请金额 * 逾期天数 * 逾期利率(%)[订单逾期利率(%)/100]
            return $orderInfo['daoqiMoney'] * $isOrderOverdue * ($orderInfo['yuqililv'] / 100);
        }

        return 0;
    }

    /**
     * 获取订单部分还款的金额.
     *
     * @param int $orderInfo 订单信息
     *
     * @return int 用户借款订单部分还款金额
     */
    public function getOrderPartMoney($orderId)
    {
        $where['OrderSn'] = $orderId['OrderSn'];
        $where['Type'] = 1;

        return db('loans_hklist')->where($where)->sum('TotalMoney');
    }

    /**
     * 获取订单豁免金额.
     *
     * @param array $orderInfo 订单信息
     *
     * @return int 订单豁免金额
     */
    public function getOrderReductionMoney($orderInfo)
    {
        return (int) db('loans_applylist')->alias('a')
            ->join('xb_loans_hklist h', 'a.ID = h.ApplyID')
            ->where(['a.ID' => $orderInfo['ID'], 'h.Type' => '3'])
            ->sum('TotalMoney');
    }

    /**
     * 订单放款.
     *
     * @param int $orderId 订单主键ID
     *
     * @return bool
     */
    public function orderLoan($orderId)
    {
        //检测订单是否处于待放款状态
        $data = db('loans_applylist')->alias('a')
		    ->where(['a.ID'=>$orderId])
            ->join('xb_mem_info m', 'a.UserID = m.ID')
            ->join('xb_renzen_bank b', 'a.UserID = b.UserID')
            ->field('a.*,m.TrueName,b.BankNo,b.BankName')
            ->find();
			if ($data['LoanStatus']==2) {
	                $res=[
						'code'=>'1',
						'msg'=>'请等待银行打款(请勿重复确认)',
						];
			return $res;
        }
        if ($data['LoanStatus'] != 1) {
	                $res=[
						'code'=>'2',
						'msg'=>'订单类型错误,请联系客服',
						];
			return $res;
            
        }
	    $sys_basicinfo = model('System')->getSystemInfo();//获取系统配置
		if ($sys_basicinfo['zdfk'] == '1') {//判断系统配置是否允许自动打款
                    $Orderget = new Orderget();
                    $Payceshi = $Orderget->get_Payceshi(); //获取支付环境
                    if ($Payceshi == '1') {//获取支付环境
                        $do['TransAmt'] = (int) $data['AdoptMoney'];
                    } else {
                        $do['TransAmt'] = '0.02';
                    }
                    $do['PartnerId'] = $Orderget->get_changpay(); //获取商户号
                    $bankDatas = Db::table('xb_renzen_bank')->field('BankNo,BankName')->where('UserID', $data['UserID'])->find();
                    if (!$bankDatas) {
							$res=[
						'code'=>'2',
						'msg'=>'获取用户银行卡信息异常',
						];
						return $res;
                    }
                    $user = Db::table('xb_mem_info')->where('ID', $data['UserID'])->find();
                    $do['AcctNo'] = $bankDatas['BankNo'];
                    $do['AcctName'] = $user['TrueName'];
                    $do['BankCommonName'] = $bankDatas['BankName'];
                    //支付参数结束
                    $changpay = new \changpay\ChangPay();
                    $datas = $changpay->payment($do); //调用畅捷代付款
                    if ($datas['AcceptStatus'] == 'S') {
                        $data_update['OutTradeNo'] = $datas['OutTradeNo']; //支付订单号
                        $data_update['LoanStatus'] = '6'; //订单状态
                        $data_update['pay'] = 4; //支付方式
                        $data_update['fail_reason']='订单提交银行成功';
                        Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
						$res=[
						'code'=>'1',
						'msg'=>'请等待银行打款(自动打款)',
						];
						return $res;
                    } else {
                        $data_update['fail_reason'] = $datas['Memo']; //支付返回错误提示
                        Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
                        $res=[
						'code'=>'2',
						'msg'=>$datas['Memo'],
						];
						return $res;
                    }
                } else {
                    $data_update['fail_reason'] = '自动放款已经关闭'; //支付返回错误提示
                    Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
					$res=[
						'code'=>'1',
						'msg'=>'请等待银行打款(手动打款)',
						];
						return $res;
                }


//      $system = model('System')->getSystemInfo();
//      if ($system['Payceshi'] == 1) {
//          $data['TransAmt'] = $data['AdoptMoney']; //放款金额
//      } else {
//          $data['TransAmt'] = '0.01'; //放款金额
//      }
//      $data['TransAmt'] = '0.01'; //测试金额 上线需删除
//      $Orderget = new Orderget();
//      $data['PartnerId'] = $Orderget->get_changpay(); //获取商户号
//      $data['AcctNo'] = $data['BankNo']; //名字
//      $data['AcctName'] = $data['TrueName']; //卡号
//      $data['BankCommonName'] = $data['BankName']; //卡号
//      $changpay = new \changpay\ChangPay();
//      $datas = $changpay->payment($data);
//      if ($datas['AcceptStatus'] == 'S') {
//          $data_update['ID'] = $data['ID']; //订单ID
//          $data_update['OutTradeNo'] = $datas['OutTradeNo']; //支付订单号
//          $data_update['LoanStatus'] = '6'; //订单状态 等待银行打款
//          $data_update['pay'] = 4; //支付方式 自动放款
//          $data_update['FkadminID'] = 119; //放款人员ID 系统放款
//      }
//      //修改订单状态
//      $result = Db::table('xb_loans_applylist')->update($data_update);
//      if ($result) {
//          return true;
//      } else {
//         $data_update['fail_reason'] = $datas['Memo']; //支付返回错误提示
//         Db::table('xb_loans_applylist')->where(['ID' => $orderId])->update($data_update);
//          $this->error = '确认失败';
//
//          return false;
//      }
    }

    /**
     * 获取订单状态描述.
     *
     * @param int $orderStatus 订单状态值
     *
     * @return string 订单状态值描述
     *
     * 订单状态 0申请中 1等待放款 2已放款 3已完成 4已取消 5已拒绝 6等待银行打款 7待人工审核
     */
    public function getOrderStatusDesc($orderStatus)
    {
        $str = '未知';
        switch ($orderStatus) {
            case 0:
                $str = '申请中';
                break;
            case 1:
                $str = '等待放款';
                break;
            case 2:
                $str = '已放款';
                break;
            case 3:
                $str = '已完成';
                break;
            case 4:
                $str = '已取消';
                break;
            case 5:
                $str = '已拒绝';
                break;
            case 6:
                $str = '等待银行打款';
                break;
            case 7:
                $str = '待人工审核';
                break;
        }

        return $str;
    }

    /**
     * 获取订单的还款信息.
     *
     * @param int $orderId 订单ID
     *
     * @return array
     */
    public function getRepaymentOrder($orderId)
    {
        return db('loans_hklist')->where(['ApplyID' => $orderId])->find();
    }

    /**
     * 获取订单还款方式(立时贷用).
     *
     * @param int $payType 还款方式
     *
     * @return
     *
     * 系统 还款方式 1线下微信 2线下支付宝 3线下银联 4线上微信 5线上支付宝 6线上银联 7豁免
     * 立时贷 还款支付方式; 如: 0.未还款 1. 主动还款 2.系统扣款 3. 支付宝转账 4. 银行转账或其它方式
     */
    public function getPayType($payType)
    {
        if (empty($payType)) {
            return 0;
        }
        if ($payType == 4 || $payType == 5 || $payType == 6) {
            return 1;
        } elseif ($payType == 1 || $payType == 2 || $payType == 3 || $payType == 7) {
            return 2;
        }
    }
}
